package com.sy.service.purchase.impl;

import com.sy.bean.purchase.ReturnOrder;
import com.sy.common.crud.BaseServiceImpl;
import com.sy.mapper.purchase.ReturnOrderDetailMapper;
import com.sy.mapper.purchase.ReturnOrderMapper;
import com.sy.service.purchase.ReturnOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
public class ReturnOrderServiceImpl extends BaseServiceImpl<ReturnOrder, ReturnOrderMapper> implements ReturnOrderService {

    String currentMaxCode; //当前最大编码 TH2024001


    @Autowired
    ReturnOrderDetailMapper returnOrderDetailMapper;

    @Autowired
    ReturnOrderMapper returnOrderMapper;

    @Transactional
    @Override
    public int save(ReturnOrder entity) {
        entity.setCode(generateCode());
        //保存退货单
        int rs=super.save(entity);
        if (rs==0)
            throw new RuntimeException("保存退货单失败");
        //保存退货明细
        rs=returnOrderDetailMapper.batchSave(entity.getId(),entity.getReturnOrderDetail());
        if (rs==0)
            throw new RuntimeException("保存退货单明细失败");
        return 1;
    }

    String generateCode() {
        String year = getYear();
        //判断当前最大编码是否存在
        if (null == currentMaxCode) {
            //如果不存在，查询当年最大编码
            currentMaxCode = baseMapper.queryMaxCode(year);
            if (null == currentMaxCode) {
                //说明不存在，生产第一个编码
                currentMaxCode = "TH" + year + "001";
            } else {
                //如果存在，新编码序号+1
                getNextCode();
            }
        } else {
            //如果存在，新编码序号+1
            getNextCode();
        }
        return currentMaxCode;
    }

    void getNextCode() {
        //TH2024001
        String prefix = currentMaxCode.substring(0, 6);
        String seq = currentMaxCode.substring(6);
        //转换数字001. tmp=1
        int tmp = Integer.parseInt(seq);
        tmp++;
        currentMaxCode = prefix + String.format("%03d", tmp);
    }

    String getYear() {
        LocalDate localDate = LocalDate.now();
        return String.valueOf(localDate.getYear());
    }

    @Override
    public int batchDelete(List<Integer> ids) {
        int rs=returnOrderMapper.batchDelete(ids);
        if (rs<1)
            throw new RuntimeException("删除退货单失败");
        rs=returnOrderDetailMapper.queryDetail(ids);
        if (rs>1) {
            rs = returnOrderDetailMapper.batchDelete(ids);
            if (rs < 1)
                throw new RuntimeException("删除退货单明细失败");
        }
        return 1;
    }
}
